package com.bqtv.sport.ui.mine

import android.content.Intent
import android.widget.TextView
import com.bqtv.sport.R
import com.google.zxing.Result
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar
import com.hjq.base.BaseActivity
import com.hjq.base.util.GlideEngine
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.king.camera.scan.AnalyzeResult
import com.king.camera.scan.CameraScan
import com.king.camera.scan.analyze.Analyzer
import com.king.zxing.BarcodeCameraScanActivity
import com.king.zxing.DecodeConfig
import com.king.zxing.DecodeFormatManager
import com.king.zxing.analyze.QRCodeAnalyzer
import com.king.zxing.util.CodeUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import java.util.concurrent.Executors

class QRCodeScanActivity : BarcodeCameraScanActivity() {
    val REQUEST_CODE_PHOTO = 0X02

    private val executor = Executors.newSingleThreadExecutor()
    var title: TitleBar? = null
    var tv_my_qrcode: TextView? = null

    companion object {
        private const val INTEXT_KEY_CONTENT = "content"
        private const val CAMERA_PERMISSION_REQUEST_CODE = 0X86
        const val REQUEST_CODE_PHOTO = 0X02

        fun start(activity: BaseActivity, listener: OnScanListener?) {
            val intent = Intent(activity, QRCodeScanActivity::class.java)
            activity.startActivityForResult(
                intent,
                object : BaseActivity.OnActivityCallback {
                    override fun onActivityResult(resultCode: Int, data: Intent?) {
                        if (listener == null || data == null) {
                            return
                        }
                        if (resultCode == RESULT_OK) {
                            val content =
                                data.getStringExtra(INTEXT_KEY_CONTENT)
                            listener.onSucceed(content)
                        } else {
                            listener.onCancel()
                        }
                    }
                })
        }
    }

    override fun initUI() {
        super.initUI()
        title = findViewById(R.id.title)
        tv_my_qrcode = findViewById(R.id.tv_my_qrcode)

        title?.setOnTitleBarListener(object : OnTitleBarListener {
            override fun onLeftClick(titleBar: TitleBar?) {
                super.onLeftClick(titleBar)
                finish()
            }

            override fun onRightClick(titleBar: TitleBar?) {
                super.onRightClick(titleBar)
                onClickPhoto()
            }
        })

        tv_my_qrcode?.setOnClickListener {
            MyQrcodeActivity.start(this)
        }
    }

    override fun initCameraScan(cameraScan: CameraScan<Result?>) {
        super.initCameraScan(cameraScan)
        // 根据需要设置CameraScan相关配置
        cameraScan.setPlayBeep(true)
    }

    override fun createAnalyzer(): Analyzer<Result?>? {
        //初始化解码配置
        val decodeConfig = DecodeConfig()
        decodeConfig.setHints(DecodeFormatManager.QR_CODE_HINTS) //如果只有识别二维码的需求，这样设置效率会更高，不设置默认为DecodeFormatManager.DEFAULT_HINTS
            .setFullAreaScan(false) //设置是否全区域识别，默认false
            .setAreaRectRatio(0.8f) //设置识别区域比例，默认0.8，设置的比例最终会在预览区域裁剪基于此比例的一个矩形进行扫码识别
            .setAreaRectVerticalOffset(0) //设置识别区域垂直方向偏移量，默认为0，为0表示居中，可以为负数
            .setAreaRectHorizontalOffset(0) //设置识别区域水平方向偏移量，默认为0，为0表示居中，可以为负数
        // BarcodeCameraScanActivity默认使用的MultiFormatAnalyzer，这里可以改为使用QRCodeAnalyzer
        return QRCodeAnalyzer(decodeConfig)
    }

    /**
     * 布局ID；通过覆写此方法可以自定义布局
     *
     * @return 布局ID
     */
    override fun getLayoutId(): Int {
        return R.layout.activity_qrcode_scan
    }

    /**
     * 点击相册
     */
    fun onClickPhoto() {
        XXPermissions.with(this)
            .permission(Permission.READ_MEDIA_IMAGES)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (allGranted) {
                        startPhotoCode()
                    }
                }
            })
    }

    private fun startPhotoCode() {
        //头像
        PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage())
            .setImageEngine(GlideEngine.createGlideEngine())
            .isDisplayCamera(false)
            .setMaxSelectNum(1)
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>) {
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    if (result.size == 0)
                        return
                    parsePhoto(result.get(0))
                }

                override fun onCancel() {}
            })
    }

    private fun parsePhoto(data: LocalMedia) {
        try {
//            val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, Uri.parse(data.path))
//            val bitmap = BitmapFactory.decodeFile(data.path)
            //异步解析
            asyncThread(Runnable {
                val result = CodeUtils.parseCode(data.realPath)
                runOnUiThread {
                    val intent = Intent()
                    intent.putExtra(
                        INTEXT_KEY_CONTENT,
                        result
                    )
                    setResult(RESULT_OK, intent)
                    finish()
                }
            })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun asyncThread(runnable: Runnable) {
        executor.execute(runnable)
    }

    override fun onScanResultCallback(result: AnalyzeResult<Result>) {
        // 停止分析
        cameraScan.setAnalyzeImage(false)
        // 返回结果
        val intent = Intent()
        intent.putExtra(INTEXT_KEY_CONTENT, result.result.text)
        setResult(RESULT_OK, intent)
        finish()
    }

    /**
     * 注册监听
     */
    interface OnScanListener {
        /**
         * 成功
         */
        fun onSucceed(content: String?)

        /**
         * 取消
         */
        fun onCancel() {}
    }
}